package com.howard.base.interceptor;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
 
public class QueryParamsInterceptor extends AbstractInterceptor {   
 
	private static final Logger logger = LoggerFactory.getLogger(QueryParamsInterceptor.class);   
  
	private static final long serialVersionUID = 1L;   
	
	private static final String ATTRIBUTE_SESSION="last.query.params";
	private static final String ACTION_SESSION="last.query.action";
	
	@SuppressWarnings("unchecked")
	@Override	  
	public  String intercept(ActionInvocation invocation) throws Exception{   
		ActionContext context=invocation.getInvocationContext();
		Map<String,Object> session=context.getSession();
		String actionNameRequest=ServletActionContext.getRequest().getRequestURI().split("/")[2];
		String actionNameSession=(String) session.get(ACTION_SESSION);
//		System.out.println("actionNameRequest="+actionNameRequest+"   actionNameSession="+actionNameSession);
		
		boolean saveParams=false;
		boolean getParams=false;
		
		//得到页面的参数
		Map<String, Object> map=context.getParameters();
		Map<String, Object> newMap=new HashMap<String, Object>();
		Iterator it=map.entrySet().iterator();
		while(it.hasNext()){
			Entry<String,Object> entry=(Entry<String,Object> ) it.next();
			if(entry.getKey().equals("saveParams"))	{saveParams=true; logger.debug("saveParams");} 
			if(entry.getKey().equals("getParams")) {getParams=true; logger.debug("getParams");}
			newMap.put(entry.getKey(), String.valueOf(((String[])entry.getValue())[0]));
		}
		
		if(saveParams){
			session.put(ATTRIBUTE_SESSION, newMap);
			session.put(ACTION_SESSION, actionNameRequest);
			logger.debug("session.setAttribute"); 
		}

		if(getParams && actionNameRequest.equals(actionNameSession)){
			Map<String, Object> mapSession=(Map<String, Object>) session.get(ATTRIBUTE_SESSION);
			context.setParameters(mapSession);
			/*Iterator it1=mapSession.entrySet().iterator();
			while(it1.hasNext()){
				Entry entry=(Entry) it1.next();
				System.out.println(entry.getKey()+"="+entry.getValue());
			}*/
		}
		
		if(null!=actionNameSession && !actionNameRequest.equals(actionNameSession)) {
			session.remove(ATTRIBUTE_SESSION);
			session.remove(ACTION_SESSION);
		}
		
		return invocation.invoke();
	}
}

